﻿namespace DimensionsHelper.LanguageService.Syntax;

public class IndexExpression : Expression
{
    private ArgumentList? _arguments;


    private Expression _object;

    internal IndexExpression(SyntaxNode? parent) : base(SyntaxKinds.IndexExpression, parent)
    {
        _object = EmptyExpression.Default;
    }


    public Expression Object => _object;


    /// <summary>
    ///     索引器的参数列表
    /// </summary>
    public ArgumentList? Arguments => _arguments;


    public void Update(Expression objectExpression)
    {
        SetChildField(ref _object, IsEmptyExpression, objectExpression);
    }


    public void Update(ArgumentList argumentList)
    {
        SetChildNullableField(ref _arguments, argumentList);
    }


    public override void AcceptVisitor<T>(SyntaxNodeVisitor<T> visitor)
    {
        Accept(visitor, Object, Arguments);
        base.AcceptVisitor(visitor);
    }
}


public static partial class NodeFactory
{
    public static IndexExpression CreateIndexExpression(SyntaxNode? parent, Expression obj,
        Expression? index)
    {
        IndexExpression expr = new(parent);
        expr.Update(obj);

        if (index != null)
        {
            ArgumentList arguments = new(expr);
            arguments.Update(index);
            arguments.Update(index.Start, index.End, index.Text);
            expr.Update(arguments);
        }

        return expr;
    }


    public static IndexExpression CreateIndexExpression(SyntaxNode? parent, Expression obj,
        ArgumentList? argumentList)
    {
        IndexExpression expr = new(parent);
        expr.Update(obj);

        if (argumentList != null)
        {
            expr.Update(argumentList);
        }

        return expr;
    }
}